package com.zm.shop.interceptor;

import com.zm.shop.common.constants.AuthCons;
import com.zm.shop.common.constants.CarCons;
import com.zm.shop.common.entity.UserEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;



/**
 * 判断用户是否登录，如果登录了就设置UID,没有登录就设置UUID
 */
@Component
public class CarInterceptor implements HandlerInterceptor {

    private ThreadLocal<String> userCarIdThreadLocal = new ThreadLocal<>();

    public String getThreadLocal() {
        return userCarIdThreadLocal.get();
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session中用户信息
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(AuthCons.LOGIN_USER);
        String userCarId = null;
        if (userEntity != null) { //用户已经登入了
            userCarId = String.valueOf(userEntity.getId());
        } else { //用户未登入
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {   // 从cookie里把UUID给userCarId
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (CarCons.CAR_ANON_NAME.equals(name)) {
                        userCarId = cookie.getValue();
                        break;
                    }
                }
            }else {  //随机存生成一个uuid赋给userCarId，并保存到cookie里
                userCarId = UUID.randomUUID().toString();
                Cookie cookie = new Cookie(CarCons.CAR_ANON_NAME, userCarId);
                cookie.setMaxAge(60 * 60 * 24 * 7); //
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        // 放到ThreadLocal中
        userCarIdThreadLocal.set(userCarId);
        return true;
    }
}
